<template>
  <div class="version" ref="base">
    <div class="title">
      <div class="create_task">
        <el-button type="primary" @click="add_version">手动添加版本</el-button>
        <el-button type="primary">获取最新版本</el-button>
      </div>
      <div class="add-version">
        <el-dialog title="手动添加版本" :visible.sync="AddVersionStatus">
          <el-form :model="versionForm" :rules="versionRules" ref="versionForm" label-width="150px"
                   class="demo-ruleForm">
            <el-form-item label="版本号" prop="version_name" style="width: 400px">
              <el-input v-model="versionForm.version_name" clearable></el-input>
            </el-form-item>
            <el-form-item label="备注信息" prop="remarks" style="width: 400px;">
              <el-input type="textarea" v-model="versionForm.remarks"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="createVersionSubmitForm('versionForm')" v-if="!add_status">立即创建
              </el-button>
              <el-button type="primary" :loading="true" v-else>立即创建</el-button>
              <el-button @click="resetForm('versionForm')">重置</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
      </div>
      <div class="time_search">
        <el-date-picker
            v-model="search_value"
            type="daterange"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions">
        </el-date-picker>
        <span style="margin-left: 4px">
        <el-button type="primary" icon="el-icon-search" class="time_search_button" @click="time_search">搜索</el-button>
      </span>
      </div>
    </div>
    <div class="package_detail">
      <el-dialog
          title="相关包详情:"
          :visible.sync="centerDialogVisible"
          width="1000px">
        <el-table :data="packInfo" stripe height="500px" style="width: 100%">
          <el-table-column prop="create_time" label="创建时间" width="300px">
            <template slot-scope="scope">
              <span>{{ time_format(scope.row.create_time) }} </span>
            </template>
          </el-table-column>
          <el-table-column prop="pack_name" label="包名" width="300px"></el-table-column>
          <el-table-column prop="pack_version" label="包版本" width="350px"></el-table-column>
        </el-table>
      </el-dialog>
    </div>
    <div class="version-detail">
      <el-table
          class="table-css"
          ref="multipleTable"
          :data="this.tableData"
          stripe
          height="calc(100vh - 180px)"
          @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column
            prop="version_name"
            label="版本号"
            width="300"
            fixed>
        </el-table-column>
        <el-table-column prop="create_time" label="创建时间" width="220">
          <template slot-scope="scope">
            <span>{{ time_format(scope.row.create_time) }} </span>
          </template>
        </el-table-column>
        <el-table-column prop="modify_time" label="更新时间" width="220">
          <template slot-scope="scope">
            <span>{{ time_format(scope.row.modify_time) }} </span>
          </template>
        </el-table-column>
        <el-table-column prop="remarks" label="备注" width="300"/>
        <el-table-column fixed="right" label="操作" width="200">
          <template slot-scope="scope">
            <el-button @click="my_detail(scope.row)" type="text" size="small" style="margin-right: 10px">详情</el-button>
            <el-button @click="add_package(scope.row)" type="text" size="small" style="margin-right: 10px">添加包信息
            </el-button>
            <el-button @click="my_delete(scope.row)" type="text" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div>
      <el-dialog
          width="60%"
          title="添加包信息"
          :visible.sync="AddPackageStatus"
          append-to-body>
        <el-form :model="packageForm" ref="packageForm" label-width="150px"
                 class="demo-ruleForm">
          <el-form-item style="margin-left: -150px">
            <el-button type="primary" @click="createPackageSubmitForm('packageForm')" v-if="!add_status">立即创建
            </el-button>
            <el-button type="primary" :loading="true" v-else>立即创建</el-button>
            <el-button @click="resetForm('packageForm')">重置</el-button>
            <el-button @click="push_package_to_list" style="margin-left: 20px">确认添加</el-button>
          </el-form-item>
          <el-form-item label="安装包名" prop="pack_name" style="width: 400px">
            <el-input v-model="packageForm.pack_name" clearable></el-input>
          </el-form-item>
          <el-form-item label="包版本信息" prop="pack_version" style="width: 400px;">
            <el-input v-model="packageForm.pack_version" clearable></el-input>
          </el-form-item>
        </el-form>
        <el-table :data="package_list" stripe height="500px" style="width: 100%">
          <el-table-column prop="create_time" label="创建时间" width="200px">
            <template slot-scope="scope">
              <span>{{ time_format(scope.row.create_time) }} </span>
            </template>
          </el-table-column>
          <el-table-column prop="pack_name" label="包名" width="150px"></el-table-column>
          <el-table-column prop="pack_version" label="包版本" width="150px"></el-table-column>
        </el-table>
      </el-dialog>
    </div>
    <div class="base_bottom">
      <div class="my_select_button">
        <el-button type="primary" style="padding: 10px 15px; margin: 0 3px 0 0" @click="select_all">全选</el-button>
        <el-button type="primary" style="padding: 10px 15px; margin: 0 3px 0 0" @click="delete_all">全部删除</el-button>
      </div>
      <div class="my-pagination">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page=this.currentPage
            :page-sizes=this.pagesizes
            :page-size=this.pagesize
            layout="total, sizes, prev, pager, next, jumper"
            :total=this.total>
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import "@/my_constants"
import {
  get_test_info,
  delete_test_info,
  filter_query,
  create_version,
  create_package,
} from "@/js/version_manage";
import ElementUI from "element-ui";

export default {
  name: "Version",
  beforeCreate() {
    // 提前获取详情
    get_test_info(1, 10).then(response => {
      this.tableData = response.data.data;
      this.total = response.data.total;
    })
  },
  data() {
    return {
      // 分页功能
      total: 0, //默认数据总数
      pagesizes: [10, 20, 50],//每页的数据条数
      pagesize: 10,//每页的数据条数
      currentPage: 1,
      tableData: [],
      packInfo: [],
      // 全选
      multipleSelection: [],
      //  过滤器
      time_filter: '',
      // 时间搜索快速获取
      search_value: '',
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      // 详情
      centerDialogVisible: false,
      // 手动添加版本
      add_status: false,  // 点击提交后不能再次点击
      AddVersionStatus: false,
      AddPackageStatus: false,
      package_list: [], // 页面显示
      package_list_to_server: [], // 实际上传
      versionForm: {
        version_name: '',
        remarks: '',
      },
      versionRules: {
        version_name: [
          {required: true, message: '请输入版本号', trigger: 'change'},
        ],
      },
      packageForm: {
        pack_version: '',
        pack_name: '',
      },
    }
  },
  methods: {
    // 时间范围
    time_search() {
      // 标准时间 转时间戳
      if (!this.search_value) {
        get_test_info(this.currentPage, this.pagesize).then(response => {
          this.tableData = response.data.data;
          this.total = response.data.total;
        })
        return
      }
      let time1 = new Date(this.search_value[0]);
      let time2 = new Date(this.search_value[1]);
      let start_time = time1.getFullYear() + '-' + (time1.getMonth() + 1) + '-' + time1.getDate()
      let end_time = time2.getFullYear() + '-' + (time2.getMonth() + 1) + '-' + time2.getDate()
      this.time_filter = {
        'start_time': start_time,
        'end_time': end_time
      }
      filter_query(this.currentPage, this.pagesize, this.time_filter).then(response => {
        this.tableData = response.data.data;
        this.total = response.data.total;
      })
    },
    // 添加版本
    createVersionSubmitForm(formName) {
      this.add_status = true
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let params = JSON.parse(JSON.stringify(this.versionForm))
          create_version(params).then(response => {
            if (response.data.status == 'success') {
              ElementUI.Message({
                showClose: true,
                message: '添加成功!',
                type: 'success'
              });
              // 清空
              this.resetForm(formName)
              // 刷新
              this.reload_data()
              // 退出
              this.AddVersionStatus = false;
              this.add_status = false;
            } else {
              ElementUI.Message({
                showClose: true,
                message: response.data.error,
                type: 'error'
              });
            }
          })
        } else {
          ElementUI.Message({
            showClose: true,
            message: '创建失败， 请确认参数填写确认再提交',
            type: 'error'
          });
          return false;
        }
      });
    },
    // 添加安装包版本信息
    createPackageSubmitForm(formName) {
      this.add_status = true
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let params = {}
          params['package_list'] = this.package_list_to_server
          params['version'] = this.version_number
          create_package(params).then(response => {
            if (response.data.status == 'success') {
              ElementUI.Message({
                showClose: true,
                message: '添加成功!',
                type: 'success'
              });
              // 清空
              this.resetForm(formName)
              // 刷新
              this.reload_data()
              // 退出
              this.AddPackageStatus = false;
              this.add_status = false;
            } else {
              ElementUI.Message({
                showClose: true,
                message: response.data.error,
                type: 'error'
              });
            }
          })
        } else {
          ElementUI.Message({
            showClose: true,
            message: '创建失败， 请确认参数填写确认再提交',
            type: 'error'
          });
          return false;
        }
      });
    },
    // 清空创建任务表单参数
    resetForm(formName) {
      this.add_status = false;
      this.$refs[formName].resetFields();
    },
    // 分页器相关
    // 当前页数
    handleSizeChange(val) {
      this.pagesize = val;
      this.currentPage = 1;
      this.reload_data()
    },
    // 每页显示条数
    handleCurrentChange(val) {
      this.currentPage = val;
      this.reload_data()
    },
    // 取消全选
    toggleSection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggRowSelection(row);
        });
      } else {
        this.$ref.multipleSelection.clearSelection();
      }
    },
    // 点击全选或选择框时出发
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 全选
    select_all() {
      this.$refs.multipleTable.toggleAllSelection();
    },
    // 时间显示格式
    time_format(time) {
      let year = new Date(time).getFullYear();
      let month = new Date(time).getMonth() + 1 < 10 ? "0" + (new Date(time).getMonth() + 1) : new Date(time).getMonth() + 1;
      let date = new Date(time).getDate() < 10 ? "0" + new Date(time).getDate() : new Date(time).getDate();
      let hh = new Date(time).getHours() < 10 ? "0" + new Date(time).getHours() : new Date(time).getHours();
      let mm = new Date(time).getMinutes() < 10 ? "0" + new Date(time).getMinutes() : new Date(time).getMinutes();
      let ss = new Date(time).getSeconds() < 10 ? "0" + new Date(time).getSeconds() : new Date(time).getSeconds();
      return year + "-" + month + "-" + date + "-" + " " + hh + ":" + mm + ':' + ss;
    },
    // 添加安装包信息
    add_package(val) {
      this.AddPackageStatus = true
      this.version_number = val.uid
      this.package_list = val.pack
      // 清空缓存
      this.package_list_to_server = []
    },
    push_package_to_list() {
      let params1 = JSON.parse(JSON.stringify(this.packageForm))
      // 上传数据
      this.package_list_to_server.push(params1)
      // 显示数据
      let params2 = JSON.parse(JSON.stringify(this.packageForm))
      params2['create_time'] = new Date
      this.package_list.push(params2)
      this.resetForm('packageForm')
    },
    // 添加测试版本
    add_version() {
      this.AddVersionStatus = true
    },
    // 详情
    my_detail(val) {
      this.centerDialogVisible = true
      this.packInfo = val.pack
    },
    // 删除
    my_delete(val) {
      if (!val) {
        return
      }
      delete_test_info(val).then(response => {
      });
      // 设置延迟，实现组件刷新
      setTimeout(() => {
        this.reload_data()
      }, 300)
    },
    // 批量删除
    delete_all() {
      delete_test_info(this.multipleSelection)
      // 设置延迟，实现组件刷新
      setTimeout(() => {
        this.reload_data()
      }, 300)
    },
    // 刷新
    reload_data() {
      setTimeout(() => {
        if (this.time_filter) {
          get_test_info(this.currentPage, this.pagesize, this.time_filter).then(response => {
            this.tableData = response.data.data;
            this.total = response.data.total;
          })
        } else if (this.field_filter) {
          filter_query(this.currentPage, this.pagesize, this.field_filter).then(response => {
            this.tableData = response.data.data;
            this.total = response.data.total;
          })
        } else {
          get_test_info(this.currentPage, this.pagesize).then(response => {
            this.tableData = response.data.data;
            this.total = response.data.total;
          })
        }
      }, 400)
    },
  },
  watch: {
    tableData: function () {
      this.$forceUpdate()
    },
  }
}
</script>

<style>
.version {
  width: 100%;
  margin: 0 0 0 5px;

}

.version:after {
  content: '';
  clear: both;
}

/* 创建任务 */
.title {
  height: 40px;
  margin: 10px 0;
}

.title:after {
  clear: both;
}

/* 关键字搜索 */
.create_task {
  float: left;
}

/* 按时间搜索 */
.time_search {
  float: right;
  margin-right: 20px;
}

.time_search_button {
  margin-left: 2px;
}

/* 创建任务按钮 */
.create_params_submit {
  margin-top: 10px;
  margin-left: 10px;
}

/* --------- end --------- */
.my_select_button {
  float: left;
}

.my-pagination {
  float: right;
  font-size: 14px;
  margin-right: 20px;
}

.base_bottom {
  margin: 10px 0;
  height: 40px;
}
</style>